package handlers

import (
	"log"
	"net/http"
	"strconv"
	"strings"

	"excel/database"
	"excel/models"

	"github.com/gin-gonic/gin"
)

// HandleGetTasks 处理获取任务列表的请求
func HandleGetTasks(c *gin.Context) {
	username := c.GetHeader("X-Username")
	roleStr := c.GetHeader("X-Role")
	if username == "" {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "请先登录"})
		return
	}

	role, err := strconv.Atoi(roleStr)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的角色信息"})
		return
	}

	// 从查询参数获取分页信息
	page := 1
	pageSize := 10
	if pageStr := c.Query("page"); pageStr != "" {
		if p, err := strconv.Atoi(pageStr); err == nil && p > 0 {
			page = p
		}
	}
	if sizeStr := c.Query("pageSize"); sizeStr != "" {
		if s, err := strconv.Atoi(sizeStr); err == nil && s > 0 {
			pageSize = s
		}
	}

	offset := (page - 1) * pageSize

	// 构建查询
	query, countQuery, params := buildTaskQuery(c, username, role)
	query += " ORDER BY created_at DESC LIMIT ? OFFSET ?"
	params = append(params, pageSize, offset)

	// 获取总数
	var total int
	err = database.DB.Get(&total, countQuery, params[:len(params)-2]...)
	if err != nil {
		log.Printf("Failed to get total count: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取数据失败"})
		return
	}

	// 获取任务列表
	var tasks []models.ExcelData
	err = database.DB.Select(&tasks, query, params...)
	if err != nil {
		log.Printf("Failed to get tasks: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取数据失败"})
		return
	}

	totalPages := (total + pageSize - 1) / pageSize

	c.JSON(http.StatusOK, gin.H{
		"data": tasks,
		"pagination": gin.H{
			"current":    page,
			"pageSize":   pageSize,
			"total":      total,
			"totalPages": totalPages,
			"hasMore":    page < totalPages,
		},
	})
}

// buildTaskQuery 构建任务查询SQL
func buildTaskQuery(c *gin.Context, username string, role int) (string, string, []interface{}) {
	var (
		query      string
		countQuery string
		params     []interface{}
		conditions []string
	)

	// 基础查询
	if role >= 10 {
		countQuery = "SELECT COUNT(*) FROM edata"
		query = "SELECT * FROM edata"
	} else {
		conditions = append(conditions, "username = ?")
		params = append(params, username)
		countQuery = "SELECT COUNT(*) FROM edata WHERE username = ?"
		query = "SELECT * FROM edata WHERE username = ?"
	}

	// 添加搜索条件
	searchParams := map[string]string{
		"task_id":       c.Query("task_id"),
		"task_name":     c.Query("task_name"),
		"live_room_id":  c.Query("live_room_id"),
		"date":          c.Query("date"),
		"task_nature":   c.Query("task_nature"),
		"task_source":   c.Query("task_source"),
		"task_priority": c.Query("task_priority"),
	}

	hasSearch := false
	for field, value := range searchParams {
		if value != "" {
			hasSearch = true
			conditions = append(conditions, field+" LIKE ?")
			params = append(params, "%"+value+"%")
		}
	}

	if hasSearch && len(conditions) > 1 {
		if role >= 10 {
			query += " WHERE "
			countQuery += " WHERE "
		} else {
			query += " AND "
			countQuery += " AND "
		}
		query += strings.Join(conditions[1:], " AND ")
		countQuery += strings.Join(conditions[1:], " AND ")
	}

	return query, countQuery, params
}
